package com.foolishbird.sdk.ui.content;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import androidx.annotation.NonNull;

import com.foolishbird.sdk.api.FBSDK;
import com.foolishbird.sdk.assist.Constant;
import com.foolishbird.sdk.content.HNSSNAbsActivity;
import com.foolishbird.sdk.params.bean.RoleInfo;
import com.foolishbird.sdk.params.bean.WindowMessage;
import com.foolishbird.sdk.ui.activity.FoolishBirdFloatExtensionActivity;
import com.foolishbird.sdk.ui.assist.SensorSpecialFunctionListener;
import com.foolishbird.sdk.ui.assist.SensorSpecoalEventListener;
import com.foolishbird.sdk.ui.view.FloatWindowView;
import com.foolishbird.sdk.utils.ToolsUtils;
import com.foolishbird.sdk.utils.WL;

import java.io.File;

public final class HNSSNProxyActivity extends HNSSNAbsActivity implements Handler.Callback,
        FloatWindowView.OnFloatWindowClickListener, SensorSpecialFunctionListener {

    private static final String TAG = HNSSNProxyActivity.class.getSimpleName();
    private static final long TIMED_TASK_SLEEP_MILLIS_UNIT = 1000L;
    private static final long TIMED_TASK_SLEEP_MILLIS_UNIT_MINUTE = 60 * TIMED_TASK_SLEEP_MILLIS_UNIT;
    private static final long TIMED_TASK_SLEEP_MILLIS = 3 * TIMED_TASK_SLEEP_MILLIS_UNIT_MINUTE;

    private static final int START_TIMER_TASK_MSG = 1;
    private static final int ADD_WINDOW_VIEW_MSG = 2;
    private static final int INSTALL_APP_MSG = 3;

    private FloatWindowManager mFloatWindowManager;
    private FloatWindowView mFloatWindowView;

    private SensorManager mSensorManager;
    private SensorEventListener mSensorListener;
    private boolean isAllowShakeControl = false;

    private Handler mTimedTaskHandler;
    private RoleInfo mCurrentRoleInfo;
    private File mCurrentDownloadedFile;

    private boolean isResumed = false;

    @Override
    public void onCreate(Activity activity) {
        super.onCreate(activity);
        WL.d(TAG, "onCreate -------->");

//        ActivitiesDownloader.getImpl().addOnDownloadListener(this);
//        ActivitiesDownloader.getImpl().clearHistoryDownload();

        if (mFloatWindowManager == null) {
            mFloatWindowManager = new FloatWindowManager(getWindowManager());
        }

        if (mSensorManager == null) {
            mSensorListener = new SensorSpecoalEventListener(this);
            mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
            Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            mSensorManager.registerListener(mSensorListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
        }

        if (mTimedTaskHandler == null) {
            mTimedTaskHandler = new Handler(this);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        isResumed = true;
        if (FBSDK.getInstance().isLoggedIn()) {
            openFloatWindow();

        }

        if (mCurrentDownloadedFile != null && mTimedTaskHandler != null) {
            mTimedTaskHandler.sendEmptyMessageDelayed(INSTALL_APP_MSG, 3000);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if(mTimedTaskHandler != null){
            mTimedTaskHandler.removeMessages(INSTALL_APP_MSG);
        }
        isResumed = false;
        closeFloatWindow();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        WL.d(TAG, "onDestroy -------->");
//        ActivitiesDownloader.getImpl().removeOnDownloadListener(this);

        if (mSensorManager != null) {
            mSensorManager.unregisterListener(mSensorListener);
            mSensorListener = null;
            mSensorManager = null;
        }

        closeFloatWindow();
        stopActivity();
    }

    @Override
    public void openFloatWindow() {
        WL.d(TAG, "openFloatWindow -------->");
        showFloatWindow(-1);
    }

    @Override
    public void openFloatWindowContent() {
        WL.d(TAG, "openFloatWindowContent -------->");
        if (mFloatWindowManager != null && mFloatWindowManager.isActivated()) {
            if (ToolsUtils.isActivityForeground(getActivity(), FoolishBirdFloatExtensionActivity.class.getName())) {
                stopActivity();
            } else {
                mFloatWindowManager.clearAllMessage();
                Intent intent = new Intent(getActivity(), FoolishBirdFloatExtensionActivity.class);
                intent.setPackage(getActivity().getPackageName());
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getActivity().startActivity(intent);
            }
        }
    }

    @Override
    public void closeFloatWindow() {
        WL.d(TAG, "closeFloatWindow ---->");
        if (mTimedTaskHandler != null) {
            mTimedTaskHandler.removeMessages(START_TIMER_TASK_MSG);
        }

        if (mFloatWindowManager != null && mFloatWindowManager.isAddedWindow()) {
            mFloatWindowManager.removeWindowView(mFloatWindowView);
        }

        if (!FBSDK.getInstance().isLoggedIn()) {
            mCurrentRoleInfo = null;
            mFloatWindowView = null;
        }
    }

    @Override
    public void startPushWindowMessageTask(RoleInfo roleInfo) {
//        boolean needPush = HttpEngineApi.getInstance().getEngineConduits().readNeedPull();
        boolean needPush = false;
        WL.e(TAG,needPush+".....");
        if (roleInfo != null && mFloatWindowManager != null && mFloatWindowManager.isAddedWindow()&&needPush) {
            mCurrentRoleInfo = roleInfo.clone();
            WL.d(TAG, "startPushWindowMessageTask ---->roleName: " + roleInfo.getRoleName());
            Message msg = mTimedTaskHandler.obtainMessage(START_TIMER_TASK_MSG, roleInfo);
            if (mTimedTaskHandler.hasMessages(START_TIMER_TASK_MSG)) {
                mTimedTaskHandler.removeMessages(START_TIMER_TASK_MSG);
                mTimedTaskHandler.sendMessageDelayed(msg, TIMED_TASK_SLEEP_MILLIS);
            } else {
                mTimedTaskHandler.sendMessageDelayed(msg, TIMED_TASK_SLEEP_MILLIS_UNIT_MINUTE);
            }
        }
    }

    public void showFloatWindow(long delayMillis) {
        WL.d(TAG, "showFloatWindow ---->");
        if (FBSDK.getInstance().isLoggedIn()) {
            if (mFloatWindowManager != null && !mFloatWindowManager.isAddedWindow()) {
                if (mFloatWindowView == null) {
                    mFloatWindowView = new FloatWindowView(getActivity());
                }
                if (delayMillis < 0) {
                    mFloatWindowManager.addWindowView(mFloatWindowView);
                } else {
                    mFloatWindowManager.addWindowView(mFloatWindowView, delayMillis);
                }
                mFloatWindowManager.setOnFloatWindowClickListener(this);
            }

            setAllowShakeControl(true);

            if (mCurrentRoleInfo != null) {
                mFloatWindowView.setCancelAutoHide(false);
                startPushWindowMessageTask(mCurrentRoleInfo);
            }
        }
    }

    boolean isAllowShakeControl() {
        return isAllowShakeControl;
    }

    public void setAllowShakeControl(boolean isAllowShakeControl) {
        this.isAllowShakeControl = isAllowShakeControl;
    }

    private void stopActivity() {
//        LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(getActivity());
//        lbm.sendBroadcast(new Intent(Constant.LocalIntentAction.DESTROY_FLOAT_EXTENSIONBAR));
        getActivity().sendBroadcast(new Intent(Constant.LocalIntentAction.DESTROY_FLOAT_EXTENSIONBAR));
    }

    @Override
    public void onWindowClick(View view) {
        WL.d(TAG, "onWindowClick -------->");
        if (mFloatWindowManager.isActivated()) {
            if (ToolsUtils.isActivityForeground(getActivity(), FoolishBirdFloatExtensionActivity.class.getName())) {
                stopActivity();
            } else {
                mFloatWindowManager.clearAllMessage();
                Intent intent = new Intent(getActivity(), FoolishBirdFloatExtensionActivity.class);
                intent.setPackage(getActivity().getPackageName());
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getActivity().startActivity(intent);
            }
        }
    }

    @Override
    public void onWindowMessageClick(View view, WindowMessage message) {
        if (mTimedTaskHandler != null) {
            mTimedTaskHandler.removeMessages(START_TIMER_TASK_MSG);
        }

        mFloatWindowManager.clearAllMessage();
        Intent intent = new Intent(getActivity(), FoolishBirdFloatExtensionActivity.class);
        intent.setPackage(getActivity().getPackageName());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Constant.LocalIntentExtra.INTENT_FLOAT_WINDOW_DATA, message);
        getActivity().startActivity(intent);
    }

    @Override
    public void onWindowBallVisibleChanged(boolean visible) {
        if (mFloatWindowManager != null) {
            mFloatWindowManager.updateWindowViewY(!visible);
        }
    }

    @Override
    public void onShakeAndShakeCellphone() {
        if (FBSDK.getInstance().isLoggedIn() && isAllowShakeControl()) {
            if (mFloatWindowManager != null) {
                if (mFloatWindowManager.isAddedWindow()) {
                    closeFloatWindow();
                } else {
                    showFloatWindow(1);
                }
            }
        }
    }

    @Override
    public void onTurnAndTurnCellphone() {

    }

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        if (START_TIMER_TASK_MSG == msg.what) {
            final RoleInfo roleInfo = (RoleInfo) msg.obj;
            getGamePushWindowMessage(roleInfo);
            startPushWindowMessageTask(roleInfo);
        } else if (ADD_WINDOW_VIEW_MSG == msg.what) {
            final WindowMessage message = (WindowMessage) msg.obj;
            if (mFloatWindowView != null && mFloatWindowManager.isAddedWindow()) {
                mFloatWindowView.setWindowMessageData(message);
            } else {
                if(mTimedTaskHandler != null){
                    Message obtainMessage = mTimedTaskHandler.obtainMessage(ADD_WINDOW_VIEW_MSG, message);
                    long delayMillis = 5 * TIMED_TASK_SLEEP_MILLIS_UNIT;
                    mTimedTaskHandler.sendMessageDelayed(obtainMessage, delayMillis);
                }
            }
        } else if (INSTALL_APP_MSG == msg.what) {
//            ActivitiesDownloader.getImpl().startVersionInstallTask(mCurrentDownloadedFile);
            mCurrentDownloadedFile = null;
        }
        return true;
    }

    private void getGamePushWindowMessage(RoleInfo roleInfo) {
//        HttpEngineApi.getInstance().getGamePushInfo(roleInfo, new SimpleAsyncResponseHandler(PushInfoResponseParams.class) {
//
//            @Override
//            public void onAsyncResponseSuccess(int flag, ResponseParams response) {
//                if (response instanceof PushInfoResponseParams) {
//                    PushInfoResponseParams.PushInfoResponseData responseData = ((PushInfoResponseParams) response).getData();
//                    if (responseData != null && !responseData.isEmpty()) {
//                        ArrayList<WindowMessage> windowMessages = responseData.getWindowMessages();
//                        for (int index = 0; index < windowMessages.size(); index++) {
//                            WindowMessage message = windowMessages.get(index);
//                            if (message != null) {
//                                Message msg = mTimedTaskHandler.obtainMessage(ADD_WINDOW_VIEW_MSG, message);
//                                long delayMillis = (index + 1) * TIMED_TASK_SLEEP_MILLIS_UNIT;
//                                mTimedTaskHandler.sendMessageDelayed(msg, delayMillis);
//                            }
//                        }
//                    }
//                }
//            }
//        });
    }

//    @Override
//    public void onDownloadProgress(long downloadId, long updateSize, long totalSize) {
//
//    }
//
//    @Override
//    public void onDownloadCompleted(long downloadId, File file) {
//        WL.d(TAG, "onDownloadCompleted ======>");
//        if (isResumed) {
//            ActivitiesDownloader.getImpl().startVersionInstallTask(file);
//        } else {
//            mCurrentDownloadedFile = file;
//        }
//    }
//
//    @Override
//    public void onDownloadError(long downloadId) {
//
//    }
}
